package com.beifu.manager.controller;

import com.beifu.manager.common.Const;
import com.beifu.manager.common.InnerPage;
import com.beifu.manager.dao.AssetTypeMapper;
import com.beifu.manager.dao.OrganizerMapper;
import com.beifu.manager.model.*;
import com.beifu.manager.service.assetoutplanservice.AssetOutPlanService;
import com.beifu.manager.service.assetoutservice.AssetOutService;
import com.beifu.manager.service.assetouttruthservice.AssetOutTruthService;
import com.beifu.manager.service.organizeservice.OrganizeService;
import com.beifu.manager.shiro.ActiveUser;
import com.beifu.manager.vo.assetout.AssetOutDetailVo;
import com.mds.manager.utils.PageUtils;
import com.mds.manager.utils.ResponseHelp;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

@SuppressWarnings("Duplicates")
@Controller
public class AssetOutController {

	@Autowired
	private AssetOutService assetOutService;
	@Autowired
	private OrganizeService organizeService;
	@Autowired
	private AssetOutPlanService assetOutPlanService;
	@Autowired
	private AssetOutTruthService assetOutTruthService;
	@Autowired
	private AssetTypeMapper assetTypeMapper;
	@Autowired
	private OrganizerMapper organizerMapper;


	private Logger logger = Logger.getLogger(AssetOutController.class);

	/**
	 * 跳转登录
	 *
	 * @param model
	 * @return
	 */
	@RequestMapping("assetOut/list")
	public String assetOutListEnter(Model model) {
		logger.info(">>跳转出库列表...");
		return "asset/out/asset_out_list";

	}


	@ResponseBody
	@RequestMapping(value= "assetOut/getList",produces= MediaType.APPLICATION_JSON_VALUE+";charset=utf-8")
	public String assetOutListGet(Model model,HttpServletRequest request) {
		logger.info(">> 进入出库列表界面..");

		Subject subject = SecurityUtils.getSubject();
		ActiveUser activeUser = (ActiveUser)subject.getPrincipal();
		String organizeId = activeUser.getOrganizeId();

		String page = request.getParameter("pageNumber");
		PageUtils Page = new PageUtils(page);


		int count = 0;
		String responseText = StringUtils.EMPTY;
		if(StringUtils.isNotBlank(organizeId)){
			count  = organizeService.countOrganizeService(organizeId);
			if(count==0||count>1){
				logger.error(">>>.没有查到对应用户的机构码,或机构码有多条");
				return ResponseHelp.responseText(Page);
			}
			responseText = dealThisUser(request, Page,organizeId, Const.User_Type.NORMAL);
		}else {
			logger.error(">>>.该用户没有配置机构码,默认为超级管理员。");
			responseText = dealThisUser(request, Page,null,Const.User_Type.SUPER_ADMIN);
		}


		logger.info("==========================================>responseText:"+responseText);
		return responseText;

	}

	private String dealThisUser(HttpServletRequest request, PageUtils page, String organizeId, String type) {
		String query_assetOutId = request.getParameter("query_assetOutId");
		String query_assetOutStatus = request.getParameter("query_assetOutStatus");

		AssetOutExample example = new AssetOutExample();
		AssetOutExample.Criteria criteria = example.createCriteria();
		example.setOrderByClause("status ASC");

		int organizeIdInt = Integer.valueOf(organizeId);
		if(Const.User_Type.NORMAL.equals(type)){
			criteria.andSrcOrganizeIdEqualTo(organizeIdInt);
		}



		//判断搜索栏条件 id
		if (!StringUtils.isEmpty(query_assetOutId)) {
			Integer query_assetOutId_int = Integer.valueOf(query_assetOutId);
			criteria.andIdEqualTo(query_assetOutId_int);
		}
		//判断搜索栏条件 状态
		if (!StringUtils.isEmpty(query_assetOutStatus)) {
			Integer query_assetOutStatus_int = Integer.valueOf(query_assetOutStatus);
			criteria.andStatusEqualTo(query_assetOutStatus_int);
		}
		page.setQueryParames(example);
		page = assetOutService.getAssetOutPages(page);
		String responseText = ResponseHelp.responseText(page);
		return responseText;
	}


	/**
	 * 查看出库管理
	 * @param request
	 * @return
	 */
	@RequestMapping("assetOut/getassetOutDetail")
	public String getAssetOutDetail(HttpServletRequest request){

		Subject subject = SecurityUtils.getSubject();
		ActiveUser activeUser = (ActiveUser)subject.getPrincipal();
		String organizeId = activeUser.getOrganizeId();
		String assetOutId = request.getParameter("id");
		AssetOutDetailVo assetOutDetail = null;
			assetOutDetail = assetOutService.getAssetOutDetailOut(assetOutId,false);


		request.setAttribute("assetOutDetailVo", assetOutDetail);

		return "asset/out/asset_out_detail";

	}

	@ResponseBody
	@RequestMapping(value = "assetOut/getAssetOutTruthList" ,produces= MediaType.APPLICATION_JSON_VALUE+";charset=utf-8")
	public String getAssetOutTruth(Model model, HttpServletRequest request){

		String assetOutId = request.getParameter("id");
		String page = request.getParameter("page");
		String limit = request.getParameter("limit");
//		String page = request.getParameter("pageNumber");
		PageUtils Page = new PageUtils();

		Page.setLimit(Integer.valueOf(limit));
		Page.setPage(Integer.valueOf(page));
		AssetOutTruthExample example = new AssetOutTruthExample();
		AssetOutTruthExample.Criteria criteria = example.createCriteria();
		Long assetOutIdint = Long.valueOf(assetOutId);
		criteria.andAssetOutIdEqualTo(assetOutIdint);
		Page.setQueryParames(example);

		PageUtils truthsWithPage = assetOutTruthService.getAssetOutTruthsWithPage(Page);

		//包装新的分页工具
		InnerPage	innerPage = new InnerPage();
		innerPage.setData(truthsWithPage.getList());
		innerPage.setCount(truthsWithPage.getCountNum());
		String responseText = ResponseHelp.responseText(innerPage);

		return responseText;
	}

	@RequestMapping("/assetOut/goAssetOutAdd")
	public String goAssetInAdd(Model model, HttpServletRequest request){
		logger.info(">> 添加备品入库单列表界面");

		//查询当前所有分类
		AssetTypeExample assetTypeExample = new AssetTypeExample();
		assetTypeExample.createCriteria();
		List<AssetType> assetTypeAll = assetTypeMapper.selectByExample(assetTypeExample);

		//查询源
		OrganizerExample organizerExample = new OrganizerExample();
		List<Organizer> destOrganizerList = organizerMapper.selectByExample(organizerExample);


		Subject subject = SecurityUtils.getSubject();
		ActiveUser activeUser = (ActiveUser)subject.getPrincipal();
		String userName = activeUser.getUserName();
		String organizeId = activeUser.getOrganizeId();
		List<Organizer> userOrganizerList = new ArrayList<Organizer>();


		int organizeIdInt = 0;
		if(StringUtils.isBlank(organizeId)){
			logger.info(">>>..该用户是超级管理员");
			userOrganizerList.addAll(userOrganizerList);
		}else {
			organizeIdInt = Integer.valueOf(organizeId);
			Organizer userOrganizer = organizerMapper.selectByPrimaryKey(organizeIdInt);
			userOrganizerList.add(userOrganizer);
			Iterator<Organizer> iterator = destOrganizerList.iterator();
			while (iterator.hasNext()){
				Organizer next = iterator.next();
				if(next.getId().equals(organizeIdInt)){
					iterator.remove();
				}
			}
		}


		request.setAttribute("assetTypeAll", assetTypeAll);
		request.setAttribute("userName", userName);
		request.setAttribute("destOrganizerList", destOrganizerList);
		request.setAttribute("userOrganizerList", userOrganizerList);



		return "/asset/out/asset_out_add";
	}

	@ResponseBody
	@RequestMapping("/assetOut/assetOutAdd")
	public String assetInAdd(Model model, HttpServletRequest request){
		logger.info(">> 添加备品入库单");

		Subject subject = SecurityUtils.getSubject();
		ActiveUser activeUser = (ActiveUser) subject.getPrincipal();


		String create_userName = request.getParameter("create_userName");
		String create_inTime = request.getParameter("create_inTime");
		String create_remark = request.getParameter("create_remark");

		String assetTypeSelect =   request.getParameter("assetTypeSelect");
		String assetTypeNum    =   request.getParameter("assetTypeNum");
		String destOrganizer   =   request.getParameter("destOrganizer"); //目标地址
		String userOrganizer   =   request.getParameter("userOrganizer");


		List<String>  assetTypeSelectArr = new ArrayList<String> ();
		List<String>  assetTypeNumArr = new ArrayList<String> ();

		if(!org.springframework.util.StringUtils.isEmpty(assetTypeSelect) && assetTypeSelect.indexOf(",") > 0){
			assetTypeSelectArr = (List<String>) Arrays.asList(assetTypeSelect.split(","));
		}else{
			assetTypeSelectArr.add(assetTypeSelect);
		}

		if(!org.springframework.util.StringUtils.isEmpty(assetTypeNum) && assetTypeNum.indexOf(",") > 0){
			assetTypeNumArr = (List<String>) Arrays.asList(assetTypeNum.split(","));
		}else{
			assetTypeNumArr.add(assetTypeNum);
		}

		String status = "0";
		assetOutService.createAsstOutOrder(activeUser.getUserId(),activeUser.getOrganizeId(),
				create_inTime,status,assetTypeSelectArr,assetTypeNumArr,create_remark,destOrganizer,userOrganizer);

		return ResponseHelp.responseText();
	}

	/**
	 * 删除备品入库单
	 * @param model
	 * @param request
	 * @param
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/assetOut/delAssetOut")
	public String delAssetIn(Model model,HttpServletRequest request){
		String ids = request.getParameter("ids");
		String[] idsArr = ids.split(",");
		assetOutService.batchDelAssetOut(idsArr);
		return ResponseHelp.responseText();
	}

}
